#!/bin/sh

DAT=`date +"%F_%T"`
INSTPATH="/conf/sbin"
echo "Install dropbear SSH2 server for embedded linux"
echo "This is the last chance to cancel the installation"
echo ""
echo "Press Enter to continue"
read T
echo "$T" > /dev/null
clear
echo "Install dropber (MULTI)"
echo ""
if [ -d /conf/dropbear ]; then
    echo -n "Backup dropbear catalogue ... "
    mv /conf/dropbear /conf/dropbear.$DAT
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        echo "FAIL"
        echo "Please, manual [re]move /conf/dropbear directory and run again this script"
        echo 1
    fi
    echo "OK"
fi
echo -n "Create /conf/dropbear directory ... "
mkdir -p /conf/dropbear
echo "OK"
echo "Backup (if exists) dropbear files"
[ -s $INSTPATH/dropbear ] && mv $INSTPATH/dropbear $INSTPATH/dropbear.$DAT
[ -s $INSTPATH/dropbearconvert ] && mv $INSTPATH/dropbearconvert $INSTPATH/dropbearconvert.$DAT
[ -s $INSTPATH/dropbearkey ] && mv $INSTPATH/dropbearkey $INSTPATH/dropbearkey.$DAT
[ -s $INSTPATH/dropbearmulti ] && mv $INSTPATH/dropbearmulti $INSTPATH/dropbearmulti.$DAT
[ -s $INSTPATH/dbclient ] && mv $INSTPATH/dbclient $INSTPATH/dbclient.$DAT
[ -s $INSTPATH/scp ] && mv $INSTPATH/scp $INSTPATH/scp.$DAT
echo "Install new files"
echo -n " - dropbearmulti   : "
cp -f ./dropbearmulti $INSTPATH/
chmod 755 $INSTPATH/dropbearmulti
echo "OK"
echo -n " - dropbear        : "
ln -s $INSTPATH/dropbearmulti $INSTPATH/dropbear
cp -f ./dropbear.8 /conf/dropbear/
echo "OK"
echo -n " - dropbearkey     : "
ln -s $INSTPATH/dropbearmulti $INSTPATH/dropbearkey
cp -f ./dropbearkey.8 /conf/dropbear/
echo "OK"
echo -n " - dropbearconvert : "
ln -s $INSTPATH/dropbearmulti $INSTPATH/dropbearconvert
echo "OK"
echo -n " - dbclient        : "
ln -s $INSTPATH/dropbearmulti $INSTPATH/dbclient
cp -f ./dbclient.1 /conf/dropbear/
echo "OK"
echo -n " - scp             : "
ln -s $INSTPATH/dropbearmulti $INSTPATH/scp
echo "OK"
echo -n " - motd            : "
cp ./motd /conf/dropbear/
echo "OK"
echo "Generate new key"
$INSTPATH/dropbearkey -t rsa -f /conf/dropbear/dropbear_rsa_host_key
echo "Add autostart dropbear into rc.sys"
echo "nice -n 10 $INSTPATH/dropbear -w -j -k > /conf/dropbear/dropbear.log 2>&1" >> $INSTPATH/rc.sys
echo "COMPLETE!"
